<script setup>
import { ref, inject, watch, onBeforeUnmount } from 'vue'
import { LineLayer, Popup } from '@antv/l7'
import axios from 'axios'
import { useCityLayers } from '@/composable/useCityLayers.js'
// 图层管理函数
const { updateLayerList } = useCityLayers()
const { map, scene } = inject('mapScene')

watch(
  [map, scene],
  async ([newMap, newScene]) => {
    if (!newMap || !newScene) return
    newMap.flyTo({
      center: [114.26459274967397, 30.5002467409972],
      zoom: 14,
      pitch: 65,
      bearing: -20,
    })
    // 获取数据
    const res = await axios.get('http://localhost:3001/Wuhan_bridge')
    // 添加桥梁图层
    const bridgeLayer = new LineLayer({
      zIndex: 1,
      name: 'bridgeLayer',
    })
    bridgeLayer
      .source(res.data)
      .size(10)
      .shape('arc3d')
      .color('name', ['#ff0000', '#00ff00', '#0000ff', '#ffff00'])
      .style({
        thetaOffset: 1,
      })
    newScene.addLayer(bridgeLayer)
    updateLayerList(newScene)

    // 创建并添加弹窗
    const popup = new Popup({})
    newScene.addPopup(popup)

    // 监听点击事件
    bridgeLayer.on('click', (e) => {
      // console.log('点击了桥梁', e)
      // 事件对象e包含了要素属性和经纬度信息  解构赋值
      const {
        feature: {
          properties: { info, name },
        },
        lngLat,
      } = e
      // 设置弹窗内容
      popup.setLngLat(lngLat)
      popup.setHTML(`<p style="font-size: 12px;">${info}</p>`)
      popup.setTitle(name)
    })
  },
  { immediate: true },
)

onBeforeUnmount(() => {
  const bridgeLayer = scene.value.getLayerByName('bridgeLayer')
  scene.value.removeLayer(bridgeLayer)
  updateLayerList(scene.value)
})
</script>

<template>
  <div>
    <h1>Bridge View</h1>
  </div>
</template>

<style scoped></style>
